//
//  M4NetworkManager.swift
//  M4
//
//  Created by YuChuang on 2024/8/7.
//

import Foundation
import Moya
import KakaJSON


private let M4EndpointClosure = { (target: M4NetworkTarget) -> Endpoint in
     var endpoint: Endpoint = MoyaProvider.defaultEndpointMapping(for: target)
     return endpoint
 }


private let M4RequestClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<M4NetworkTarget>.RequestResultClosure) -> Void in
     do {
         var request = try endpoint.urlRequest()
         
         request.timeoutInterval = 60
         
         if let requestData = request.httpBody {
             print("requestUrl：\(request.url!)" + "\n" + "\(request.httpMethod ?? "")" + "sendParam" + "\(String(data: request.httpBody!, encoding: String.Encoding.utf8) ?? "")")
         } else {
             print("requestUrl：\(request.url!)" + "\(String(describing: request.httpMethod))")
         }

         if let header = request.allHTTPHeaderFields {
             print("requestHeader：\(header)")
         }

         done(.success(request))
     } catch {
         done(.failure(MoyaError.underlying(error, nil)))
     }
     
 }

struct M4NetworkManager {
    
    typealias M4NetworkProgress = (CGFloat) -> Void
    
    typealias M4NetworkCompletion = (M4NetworkResultModel) -> Void
    
    func M4Request(_ target: M4NetworkTarget, _ needLoading: Bool = true, progress: M4NetworkProgress? = nil, completion: @escaping M4NetworkCompletion) {
        
        MoyaProvider(endpointClosure: M4EndpointClosure, requestClosure: M4RequestClosure, plugins: [M4NetworkPlug(M4isNeedLoading: needLoading)], trackInflights: false).request(target, callbackQueue: DispatchQueue.main) { progressResponse in
            progress?(CGFloat(progressResponse.progress))
        } completion: { result in
            let networkResult = result.M4mapNetworkResult()
            completion(networkResult)
        }
    }
}
